<template>
  <div>
    <div class="app-container">
      <!-- <h-table-list
        border
        type="local"
        :page-sizes="[10, 20]"
        :data="device_patrol_records.records1"
        @size-change="handleSizeChange"
        :columns="columns"
        :showPagination="false"
        :form-options="formOptions"
        @select="selectRows"
        ref="refTable"
        @expand-change="clickTable"
        :span-method="combineSpan"
      >
        <template slot="preview-column" slot-scope="scope">
          <p>
            <i v-if="scope.row.state==0" class="iconfont deviceicon-dian-0"></i>
            <i v-if="scope.row.state==1" class="iconfont deviceicon-dian-1"></i>
            <i v-if="scope.row.state==2" class="iconfont deviceicon-dian-2"></i>
          {{ scope.row.state |formatState}}</p>
        </template>

        <template slot="operate-column" slot-scope="scope">
          <el-table-column type="expand" label="操作" width="100">
            <template slot-scope="scope">
              <h-table-list
                border
                type="local"
                :page-sizes="[10, 20]"
                :data="device_patrol_records.records2"
                @size-change="handleSizeChange2"
                :columns="columns2"
                :paginationInfo="paginationInfo2"
                :form-options="formOptions2"
              ></h-table-list>
            </template>
          </el-table-column>
        </template>
      </h-table-list> -->
      <FormDetailNoImg class="plan-record-head" :data-model="[recordData]" />
      <div class="table-record">
        <el-table

          :data="device_patrol_records.records1"
          border
          style="width: 100%"
          @expand-change="clickTable"
        >
          <el-table-column
            prop="part"
            label="点检部位"
            width="180"
          />
          <el-table-column
            prop="content"
            label="点检内容"
            width="180"
          />
          <el-table-column
            prop="standard"
            label="点检基准"
          />
          <el-table-column
            prop="method"
            label="点检方法"
          />
          <el-table-column
            prop="upPicFlag"
            label="上传图片"
          />
          <el-table-column
            prop="upVideoFlag"
            label="上传视频"
          />
          <el-table-column type="expand" label="操作" width="100">
            <template slot-scope="scope">
              <h-table-list
                border
                type="local"
                :page-sizes="[10,20]"
                :data="device_patrol_records.records2"

                :columns="columns2"
                :pagination-info="paginationInfo2"
                :form-options="formOptions2"
              >
                <template slot="operate-picList" slot-scope="scope">
                  <el-button @click="()=>{lookImg(scope.row.picList[5].viewPath)}">查看</el-button>
                  <el-button @click="()=>{lookImg(scope.row.picList[5].viewPath)}">下载</el-button>
                </template>
                <template slot="operate-videoList" slot-scope="scope">
                  <el-button>查看</el-button>
                  <el-button>下载</el-button>
                </template>
              </h-table-list>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import FormDetailNoImg from '@/components/formEdit/formDetailNoImg'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import ListOpearteButton from '@/components/AllButton/button2'
import tableButton from '@/components/AllButton/button3'
import { mapGetters } from 'vuex'

export default {
  name: 'DevicePatrolCheck',
  components: {
    Pagination,
    tableButton,
    ListOpearteButton,
    FormDetailNoImg
  },
  directives: { waves },
  filters: {
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      recordData: {},
      hasSelectRows: [],
      dialogFormVisible: false,
      loadList: false,
      paginationInfo2: {
        sizeChange: e => {
          console.log(e)
        },
        currentChange: e => {
          this.$store.dispatch('device_patrol_records/setListSearchParams', {
            current: e
          })
          this.getList(
            Object.assign(
              {},
              this.$store.state.device_patrol_records.listSearchParams
            )
          )
        },
        current: 1,
        total: 10
      },
      formOptions: {
        inline: true,
        submitBtnText: '搜索',
        showSearchBtn: false,
        showResetBtn: false,
        searchParamsHandler: () => {
          console.log('搜索')
          this.getList(
            this.$store.state.device_patrol_records.listSearchParams
          )
        },
        changevalue: params => {
          //   const forms=this.formOptions.forms.map(e=>{
          //      const key=e.prop
          //      e.defaultValue=params[key]
          //     return e
          //    })
          //  console.log(forms)
          console.log(params)
          this.$store.dispatch(
            'device_patrol_records/setListSearchParams',
            params
          )
        },
        resetBtnCallback: () => {
          this.$store.dispatch('device_patrol_records/setListSearchParams', {})
          this.getList(
            this.$store.state.device_patrol_records.listSearchParams
          )
        },
        forms: [
          {
            prop: 'planName',
            label: '计划名称',
            itemWidth: 200,
            labelPosition: 'right',
            labelWidth: 100,
            readonly: true,
            placeholder: 'A计划'
          },
          {
            prop: 'assetName',
            label: '设备名称',
            defaultValue: 'A11',
            itemWidth: 200,
            labelPosition: 'right',
            labelWidth: 100,
            readonly: true,
            placeholder: 'A计划'
          },

          {
            prop: 'assetNumber',
            label: '设备编号',
            itemWidth: 200,
            labelPosition: 'right',
            labelWidth: 100,
            readonly: true,
            placeholder: 'A计划'
          }
        ]
      },
      columns: [
        // {type:"selection",label:"序号"},
        { prop: 'part', label: '巡检部位' },
        { prop: 'content', label: '巡检内容' },

        { prop: 'standard', label: '巡检基准' },
        {
          prop: 'method',
          label: '巡检方法'
        },

        { prop: 'membName', label: '上传图片' },
        { prop: 'upVideoFlag', label: '上传视频' },
        // {type:"expand",label:"展开"},
        {
          // type:"expand",
          prop: 'operate',
          label: '',
          labelWidth: 0,
          slotName: 'operate-column'
          // fixed: "right",
        }
      ],
      columns2: [
        { type: 'selection', label: '序号' },
        { prop: 'dueStartTime', label: '任务执行时间' },
        { prop: 'itemState', label: '任务执行状态' },

        { prop: 'userName', label: '实际巡检员' },
        {
          prop: 'dueEndTime',
          label: '实际完成时间'
        },

        { prop: 'day', label: '任务用时(分)' },
        { prop: 'picList', label: '巡检图片' },
        // {type:"expand",label:"展开"},
        {
          // type:"expand",
          prop: 'videoList',
          label: '巡检视频',
          minWidth: 180,
          slotName: 'operate-column'
          // fixed: "right",
        }
      ],
      tableData: []
    }
  },

  watch: {
    formChange: () => {}
  },
  computed: {
    ...mapState(['device_patrol_records', 'app'])
  },
  created() {
    // 初始获取几个基本数据,分别为操作状态,按钮权限等  用于处理页面切换的操作
    (this.formOptions.forms = this.formOptions.forms.map(e => {
      const key = e.prop
      const data = this.$store.state.device_patrol_records.listSearchParams
      e.defaultValue = data[key] || ''
      return e
    })),
    // this.submitHandler=this.searchWithParams
    this.$store
      .dispatch(this.$store_url_button, {
        add: this.add,
        export: this.export,
        delete: this.delete,
        edit: this.edit,
        detail: this.detail,
        using: this.using,
        useless: this.useless,
        downloadTemplete: this.downloadTemplete,
        downloadIdentify: this.downloadIdentify
      })
      .then(async() => {
        // await this.$store.dispatch("app/getCodeList", ["assetType","department"]); //code转码

        // const department=this.listTotree(this.$store.state.app.allCode.department)
        // const assetType=this.listTotree(this.$store.state.app.allCode.assetType)
        // (this.formOptions.forms)[5].options=obj
        // this.$set(this.formOptions.forms[3],"options",department)
        // this.$set(this.formOptions.forms[5],"options",assetType)
        console.log(this.formOptions, '转换结果111')
        // console.log(this.$store.state)
        const { fullPath } = this.$route
        const id = localStorage.getItem(fullPath)
        this.getList(id) // 表格数据
      })

    // this.listQuery=this.$store.state.basicEquipment.listSearchParams||{}  //操作状态
  },
  methods: {
    clickTable(row, index, e) {
      console.log('点击展开', row)
      this.getList2(row)
    },
    combineSpan({ row, column, rowIndex, columnIndex }) {
      if (column == 6) {
        return [1, 6]
      }
    },
    //  throttle(fn, delay,row) {
    //   const that =this
    //   return function() {
    //       if (!throttle.timer) {
    //           that.loadThisRecord(row)
    //           //fn.apply(this, arguments);
    //       }
    //       throttle.timer = setTimeout(function() {
    //           throttle.timer = true;
    //       }, delay);
    //   }
    //   },

    // 勾选
    selectRows(selection, row) {
      console.log(selection)
      console.log(row)
      this.hasSelectRows = selection
    },
    // 对于多级下拉的code组装需要按照elementUi的组件格式,数据从vuex获取
    listTotree(list) {
      var listData = [...list]
      var map = {}
      var node
      var tree = []
      var i
      for (i = 0; i < listData.length; i++) {
        map[listData[i].id] = listData[i]
        listData[i]['value'] = listData[i].id
        listData[i]['label'] = listData[i].typeName || listData[i].organName
        // listData[i].children = [];
      }
      for (i = 0; i < listData.length; i++) {
        node = listData[i]
        if (node.parentId == 0) {
          tree.push(node)
        } else {
          // map[node.parentId].children?map[node.parentId].children:map[node.parentId].children=[] //这里是为了配合ele组件
          // map[node.parentId].children.push(node);
          // delete node.children
        }
      }
      return tree
    },
    // 自定义该业务模块下的按钮方法
    // 启用
    using(row) {
      this.$store.dispatch('device_patrol_records/useDevice', row)
      console.log('using', row)
    },
    // 停用
    useless(row) {
      this.$store.dispatch('device_patrol_records/uselessDevice', row)
    },
    add(row) {
      this.$router.push('/plant-check/component/add-plan/index')
    },
    edit(row) {
      this.$store.dispatch('device_patrol_records/setDeviceBasicId', row.id)
      localStorage.setItem('/plant-check/component/add-plan/index', row.id)
      this.$router.push('/plant-check/component/add-plan/index')
      console.log('edit')
    },
    downloadIdentify(row) {
      console.log('下载设备标识卡')
      this.dialogFormVisible = true
    },
    async downloadTemplete(ids) {
      console.log('下载导出模板')
      const download = await this.$store.dispatch(
        'device_patrol_records/downloadTemplete'
      )
      // window.open(download.)
      console.log(download)
      window.open(download)
    },
    delete(row) {
      console.log(row)
      this.$confirm(
        `确认删除？?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.$store
            .dispatch('device_patrol_records/deleteDeviceInfo', row.id)
            .then(response => {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.getList()
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '删除失败'
              })
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    update() {},
    detail(row) {
      console.log(row)

      localStorage.setItem('/plant-check/component/add-plan/detail', row.id)
      this.$store.dispatch(
        'device_patrol_records/setDeviceBasicId',
        row.assetId
      )
      this.$router.push('/plant-check/component/add-plan/detail')
    },
    import() {},
    async export() {
      console.log('导出')
      console.log(this.hasSelectRows)
      const data = this.hasSelectRows
      const res = await this.$store.dispatch(
        'device_patrol_records/exportFile',
        data
      )
      window.open(res.data)
    },
    // 弹窗的关闭
    cancel() {
      console.log('关闭弹窗')
      this.dialogFormVisible = false
    },
    // 更新弹窗数据
    updateDialog() {
      console.log('更新并关闭弹窗')
      this.dialogFormVisible = false
    },
    // 搜索按钮
    searchWithParams() {
      console.log('搜索')
    },
    async getList(args) {
      // this.listLoading = true
      console.log(args)

      const data = await this.$store.dispatch(
        'device_patrol_records/requestDeviceList1',
        args
      )

      const e = {
        title: '计划基本信息',
        content: [{ label: '计划名称', value: data.planName },
          { label: '设备名称', value: data.deviceName },
          { label: '设备编号', value: data.assetNumber }]
      }
      this.$set(this, 'recordData', e)
      // this.paginationInfo.total=this.$store.state.device_patrol_records.total1
    },
    async getList2(args) {
      // this.listLoading = true
      console.log(args)

      await this.$store.dispatch(
        'device_patrol_records/requestDeviceList2',
        args.planItemId
      )
      this.paginationInfo2.total = this.$store.state.device_patrol_records.total2
    },
    handleFilter(args) {
      this.listQuery.page = 1
      this.getList(args)
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },
    handleCreate() {
      // this.resetTemp();
      // this.dialogStatus = "create";
      // this.dialogFormVisible = true;
      // this.$nextTick(() => {
      //   this.$refs["dataForm"].clearValidate();
      // });
      this.dialogFormVisible = true
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row) {
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    }
  }
}
</script>
